package com.rao.gmall.web.all.controller;

import com.rao.gmall.feign.search.SkuEsFeignClient;
import com.rao.gmall.model.list.SearchParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author nzmxfan
 * @create 2021-08-15-15:54
 */
@Slf4j
@Controller
public class SearchListController {

    @Autowired
    SkuEsFeignClient skuEsFeignClient;

    /**
     * 根据条件进行查询，在该处组合成前端需要的数据类型，添加到 request域（model） 中并返回
     * @param searchParam
     * @param model
     * @return
     */
    @GetMapping("/list.html")
    public String search(SearchParam searchParam, Model model){
        // 1、远程调用检索服务的请求
        log.info("检索携带的参数：{}",searchParam);

        // 2、根据请求不同条件，让检索服务进行检索
        Map<String, Object> result = skuEsFeignClient.searchGood(searchParam);
        // 远程查询到的所有数据放进去
        // trademarkList、attrsList、goodsList、total、pageSize、pageNo、totalPages
        model.addAllAttributes(result);

        //检索条件回显给页面
        model.addAttribute("searchParam", searchParam);

        String urlParam = buildUrlParam(searchParam);
        //每次跳到页面，都会带上完整的 urlParam 串
        model.addAttribute("urlParam", urlParam);
        //回显排序规则  orderMap   type/sort
        Map<String, Object> orderMap = buildOrderMap(searchParam);

        model.addAttribute("orderMap",orderMap);

        //构建品牌面包屑
        String trade = buildTrademarkParam(searchParam);
        model.addAttribute("trademarkParam",trade);


        //构建属性的面包屑  attrId/attrName/attrValue
        List<Map<String,Object>> propsParamList = buildPropsParamList(searchParam);
        model.addAttribute("propsParamList",propsParamList);

        //渲染.....
        return "list/index";
    }

    private List<Map<String, Object>> buildPropsParamList(SearchParam searchParam) {
        List<Map<String, Object>> list = new ArrayList<>();
        //attrId/attrName/attrValue
        //props=1:2800-4499:价格  &props=2:%206.95英寸及以上:屏幕尺寸
        if(searchParam.getProps() != null && searchParam.getProps().length > 0){
            for (String prop : searchParam.getProps()) {
                String[] split = prop.split(":");
                Map<String, Object> propMap = new HashMap<>();
                propMap.put("attrId",split[0]);
                propMap.put("attrName",split[2]);
                propMap.put("attrValue",split[1]);

                list.add(propMap);
            }
        }

        return list;
    }

    private String buildTrademarkParam(SearchParam searchParam) {
        if(!StringUtils.isEmpty(searchParam.getTrademark())){
            //trademark=1:小米
            return "品牌:"+searchParam.getTrademark().split(":")[1];
        }
        return null;
    }

    private Map<String, Object> buildOrderMap(SearchParam searchParam) {
        Map<String, Object> orderMap = new HashMap<>();
        if (!StringUtils.isEmpty(searchParam.getOrder())) {
            //1:desc
            String[] split = searchParam.getOrder().split(":");
            orderMap.put("type", split[0]);
            orderMap.put("sort", split[1]);
            return orderMap;
        } else {
            orderMap.put("type", "1");
            orderMap.put("sort", "desc");
            return orderMap;
        }
    }

    /**
     * 根据前端传来的参数动态拼装出一个完整的url地址。方便前端下次直接使用
     * @param searchParam
     * @return
     */
    private String buildUrlParam(SearchParam searchParam) {
        //list.html?&&&
        StringBuilder builder = new StringBuilder();

        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            builder.append("&keyword="+searchParam.getKeyword());
        }

        //category3Id=61
        if(!StringUtils.isEmpty(searchParam.getCategory3Id())){
            builder.append("&category3Id="+searchParam.getCategory3Id());
        }

        //trademark=1:小米
        if(!StringUtils.isEmpty(searchParam.getTrademark())){
            builder.append("&trademark="+searchParam.getTrademark());
        }

        //props=410:不要乱删:不要乱删&props=407:Android:系统1
        if(searchParam.getProps()!=null && searchParam.getProps().length>0){
            for (String prop : searchParam.getProps()) {
                builder.append("&props="+prop);
            }
        }

        String s = builder.toString();


        return "list.html?"+s;
    }
}
